//结算单管理

interface IFeeSettleManagentViewModel extends IBaseViewModel<IFeeSettleManagentQueryTerms>{
    /**
     * ui-grid控制
     */
    gridOptions: uiGrid.IGridOptionsOf<FeeSettleBillListItemResponse>;
    /**
     * 时间日期格式
     */
    dateFormat: "{format:'YYYY.MM.DD HH:mm'}";
    /**
     * 付款方式下拉
     */
    paymentMethodDropDown:ValueListItemResponse[];
    /**
     * 费用状态下拉
     */
    feeStatusListDropDown:ValueListItemResponse[];
    /**
     * 结算人员下拉
     */
    reckonerIdListDropDown:EmployeeListItemResponse[];
    /**
     * 审核 禁用/显示
     */
    canSettleAudit:boolean;
    /**
     * 跳转结算单审核详情
     */
    settleAudit:()=> void;
    /**
     * 查看详情
     */
    settleDetail:()=>void;
    /**
     * 结算单退回
     */
    settleReturn:()=>void;
    /**
     * 结算单付款
     */
    settlePay:()=>void;
    /**
     * 打印
     */
    printFee:(data:feeSettleBillVoucherResponse)=>void;
    /**
     * 打印事件
     */
    print:()=>void;
    /**
     * 列表高
     */
    heightA:number;
}

/**
 * 查询条件
 */
interface IFeeSettleManagentQueryTerms{
    /**
     * 应付总编号
     */
    feeBillCode:string;
    /**
     * 结算承运商
     */
    carrier:string;
    /**
     * 付款方式
     */
    paymentMethod:string;
    /**
     * 费用金额
     */
    feeMoney:string;
    /**
     * 结算起始时间
     */
    startTime:string;
    /**
     * 结算结束时间
     */
    endTime:string;
    /**
     * 结算人员
     */
    reckoner:string;
    /**
     * 费用状态
     */
    feeStatus:string;
    /**
     * 发货地址
     */
    originAddress:string;
    /**
     * 送货地址
     */
    destinationAddress:string;
    /**
     * 合同号
     */
    contractNumber:string;
    /**
     * 是否检查可支付
     */
    isCheckCanPay:boolean;
}

class IFeeSettleManagentController extends ListController<IFeeSettleManagentViewModel,IFeeSettleManagentQueryTerms>{
    gridApi: uiGrid.IGridApiOf<FeeSettleBillListItemResponse>;
    /**
     * 单选
     */
    multiSelect:boolean = false ;
    /**
     * 费用状态
     */
    feeStatus:string = "4";
    /**
     * 费用状态4/6/7
     */
    feeStatusList:string = "4";
    /**
     * 排序字段枚举
     */
    orderBy:number = 0;
    /**
     * 是否升序
     */
    asc:boolean = true;
    /**
     * 编号id
     */
    id:string ="" ;

    constructor($scope:IFeeSettleManagentViewModel,private feeService:IFeeService, private authorizationService:IAuthorizationService,
    private valueService:IValueService, private employeeService:IEmployeeService, private $ngBootbox: BootboxService, 
    private $state: angular.ui.IStateService, private routeService:routeService,private LodopFuncsService:LodopFuncsService,private $location:ng.ILocationService,
    private commonService:ICommonService){
        super($scope);
        this.init();
    }

    init():void{
        super.init();

        /**
         * 审核 禁用/显示
         */
        this.$scope.canSettleAudit = false;

        this.$scope.queryTerms = {
           feeBillCode:"",
           carrier:"",
           paymentMethod:"",
           feeMoney:"",
           startTime:"",
           endTime:"",
           reckoner:"",
           feeStatus:"4",
           originAddress:"",
           destinationAddress:"",
           contractNumber:"",
           isCheckCanPay:false
        };

        this.$scope.gridOptions = {
            enableSelectAll: false,//全选禁用
			enableFullRowSelection: true,
			paginationPageSizes: [10, 20, 30],
			useExternalPagination: true,
			useExternalSorting: true,
			enableColumnResizing: true,
            columnDefs: [
                { displayName: '应付总编号', field: 'billCode', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, width: '12%' },
                { displayName: '结算承运商', field: 'carrier', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, },
                { displayName: '费用数量', field: 'feeCount', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, width: '8%' },
                { displayName: '付款方式', field: 'paymentMethod', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, width: '8%' },
                { displayName: '费用金额', field: 'totalMoney', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, width: '8%' },
                { displayName: '费用状态', field: 'feeStatus', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, width: '8%' },
                //{ displayName: '审核人员', field: 'auditedUser', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, },
                { displayName: '结算人员', field: 'reckonerName', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, },
                //{ displayName: '付款人员', field: 'payUser', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, },
                { displayName: '结算时间', field: 'settleTime', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, width: '10%' },
                { displayName: '付款时间', field: 'payTime', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, width: '10%' }
            ],
            onRegisterApi:(gridApi) => {
                this.gridApi = gridApi;
                gridApi.pagination.on.paginationChanged(this.$scope,(skipSize,pageSize)=>{
                    this.paginationChanged(skipSize,pageSize,this.$state);
                });
                // gridApi.pagination.on.paginationChanged(this.$scope, this.paginationChanged);
                gridApi.core.notifyDataChange("options");
                gridApi.core.on.sortChanged(this.$scope, this.sortChange);
                gridApi.selection.on.rowSelectionChanged(this.$scope, this.selectChange);
            } 
        }

        //单选
        this.$scope.gridOptions.multiSelect = false;

        this.query();

        $('#opendataTime').click(function () {
		    $('#dataTime').datetimepicker('show');
		});
		$('#opendataTimeEnd').click(function () {
		    $('#dataTimeEnd').datetimepicker('show');
		});

        this.isAuth();
        this.loadPaymentMethodDropDown();
        this.loadFeeStatusListDropDown();
        this.loadReckonerIdListDropDown();

        this.$scope.settleAudit = this.settleAudit;
        this.$scope.settleDetail = this.settleDetail;
        this.$scope.settleReturn = this.settleReturn;
        this.$scope.settlePay = this.settlePay;


        this.LodopFuncsService.getRoute(this.routeService.print.url);
        //this.$scope.print = this.print; 
        this.$scope.printFee = this.printFee;    

    }
    
    /**
     * 加载数据
     */
    loadData(queryTerms:IFeeSettleManagentQueryTerms,skip:number,count:number):void{
        this.feeStatusList =  this.queryTerms.feeStatus;
        
        if(this.queryTerms.feeStatus == "10") { this.feeStatusList = "10,11" };
        if(this.queryTerms.feeStatus == "" || !this.queryTerms.feeStatus ) { this.feeStatusList = "4,6,7,8,9,10,11" }
        this.feeService.getFeeSettleBillList(this.orderBy.toString(), this.asc, this.queryTerms.feeBillCode, "", this.queryTerms.carrier, this.queryTerms.paymentMethod, queryTerms.startTime, queryTerms.endTime, 
        this.queryTerms.feeMoney, this.queryTerms.reckoner, this.queryTerms.contractNumber, this.feeStatusList, this.queryTerms.originAddress, this.queryTerms.destinationAddress,this.queryTerms.isCheckCanPay,skip,count).then((result)=>{
            // this.$scope.gridOptions.totalItems = result.data.total;

                this.$scope.gridOptions.data = result.data.data;
                
                this.$scope.heightA = ((this.$scope.gridOptions.data.length * 39) + 95);

            if (skip == 0) {
                this.$scope.gridOptions.paginationCurrentPage = 1;
            }
            this.$scope.querying = false;
        }, error => {
            this.$scope.querying = false;
        });
       
    }

    getListCount():void{
         /**获取列表总数 */
         this.feeStatusList =  this.queryTerms.feeStatus;
         
         if(this.queryTerms.feeStatus == "10") { this.feeStatusList = "10,11" };
         if(this.queryTerms.feeStatus == "" || !this.queryTerms.feeStatus ) { this.feeStatusList = "4,6,7,8,9,10,11" }
         this.feeService.getFeesettlebillcount(this.queryTerms.feeBillCode, "", this.queryTerms.carrier, this.queryTerms.paymentMethod, this.queryTerms.startTime, this.queryTerms.endTime, 
         this.queryTerms.feeMoney, this.queryTerms.reckoner, this.queryTerms.contractNumber, this.feeStatusList, this.queryTerms.originAddress, this.queryTerms.destinationAddress).then((res)=>{
             this.$scope.gridOptions.totalItems=res.data.extData;
         })
    }
    localHistory():void{
        super.localHistory(this.$state)
    }
    getHistory():void{
        super.getHistory(this.$state,this.$location)
    }

    /**
     * 排序事件触发
     */
    sortChange = (grid: uiGrid.IGridInstanceOf<FeeSettleBillListItemResponse>, sortColumns: Array<uiGrid.IGridColumnOf<FeeSettleBillListItemResponse>>) => {
        if(!(sortColumns.length === 0)){
            if(sortColumns[0].sort.direction != undefined){
                let sortItem = sortColumns[0];
            switch (sortItem.name) {
                case "billCode": {
                    this.orderBy = 1;
                } break;
                case "carrier": {
                    this.orderBy = 2;
                } break;
                case "feeCount": {
                    this.orderBy = 3;
                } break;
                case "paymentMethod": {
                    this.orderBy = 4;
                } break;
                case "totalMoney": {
                    this.orderBy = 5;
                } break;
                case "feeStatus": {
                    this.orderBy = 6;
                } break;
                case "reckonerName": {
                    this.orderBy = 7
                } break;
                case "settleTime": {
                    this.orderBy = 8;
                } break;
                case "payTime": {
                    this.orderBy = 9;
                } break;
            }
            this.asc = sortItem.sort.direction == "asc";
        }
     }
        this.reload();
     }  
    
    
    /**
     * 单选
     */
    selectChange = (row: uiGrid.IGridRowOf<FeeSettleBillListItemResponse>) => {
        row.isSelected ? this.id = row.entity.id : this.id = "" ;
    }

    /**
     * 审核 禁用/显示
     */
    isAuth=()=>{
        this.authorizationService.auth('24E0A026891BC3900A8B00904320E5DB34A1132F9AD6283D').then((res)=>{
            this.$scope.canSettleAudit = res.data.extData ;
        });
    }

    /**
     * 付款方式下拉
     */
    loadPaymentMethodDropDown():void{
        this.$scope.paymentMethodDropDown = this.valueService.getPaymentMethodList().data;
    }

    /**
     * 费用状态下拉
     */
    loadFeeStatusListDropDown():void{
        /**
         * 费用状态
         */
        let feeStatusList = [] ;
        let  FeeStatusList = this.valueService.getFeeStatusList().data;
        FeeStatusList.splice(0,3);
        FeeStatusList.splice(1,1);
        this.$scope.feeStatusListDropDown = FeeStatusList;
    }

    /**
     * 结算人员下拉
     */
    loadReckonerIdListDropDown():void{
        this.employeeService.getbytype("6",  0, -1).then(result => {
            this.$scope.reckonerIdListDropDown = result.data.data;
        });
    }

    /**
     * 跳转结算单审核详情
     */
    settleAudit=()=>{
        if(this.id == "" || this.id == undefined){
            this.$ngBootbox.alert('请选择结算单');
        }else{
            this.feeService.getFeeSettleBillDetail(this.id).then((res)=>{
                if(res.data.feeStatus == "4" ){
                    this.$state.go('app.fee.fee_settle_audit',{ settleId:this.id, name:'audit' });
                }else{
                    this.$ngBootbox.alert('审核的结算单必须为已结算状态');
                }
            });
            
        }
    }

    /**
     * 查看详情
     */
    settleDetail=()=>{
        if(this.id == "" ){
            this.$ngBootbox.alert('请选择结算单');
        }else{
            this.$state.go('app.fee.fee_settle_detail',{ settleId:this.id, name:'settle' });
        }
    }

    /**
     * 结算单退回
     */
    settleReturn=()=>{
        if(this.id == ""){
            this.$ngBootbox.alert('请选择结算单');
        }else{
            this.$ngBootbox.confirm('确定退回结算单吗?').then((result)=>{
                this.feeService.getFeeSettleBillDetail(this.id).then((res)=>{
                    if(res.data.feeStatus=="6" || res.data.feeStatus=="9" ){
                        this.feeService.payerReturn(this.id).then((res)=>{
                            this.$scope.gridOptions.paginationCurrentPage = 1;
                            this.reload();
                        });
                    }else{
                        this.$ngBootbox.alert("退回的结算单必须为已审核状态");
                    }
                });
            });
        }
    } 

    /**
     * 结算单付款
     */ 
    settlePay=()=>{
        if(this.id == ""){
            this.$ngBootbox.alert('请选择结算单');
        }else{
            this.$ngBootbox.confirm('确定付款吗?').then((res)=>{
                this.feeService.getFeeSettleBillDetail(this.id).then((result)=>{
                    if(result.data.feeStatus == "6" || res.data.feeStatus=="9"){
                        this.feeService.paid(this.id).then((re)=>{
                            this.$scope.gridOptions.paginationCurrentPage = 1;
                            this.reload();
                        });
                    }else{
                        this.$ngBootbox.alert('付款的结算单必须为已审核状态');
                    }
                });
            });
        }
    }

    /**
     * 打印
     */  
    printFee=(data:feeSettleBillVoucherResponse)=>{
        var time = this.commonService.transformTime(new Date , "yyy年MM月dd日");
        if(this.id == "" ){
            this.$ngBootbox.alert('请选择一项进行打印');
            return;
        } 
        this.feeService.feeSettleBillVoucher(this.id).then((res)=>{
            var imgUrl = this.routeService.print.reimbursement;
            this.getReimbursement(res.data.settleTime, res.data.holder, res.data.bankCode, res.data.paymentMethod, res.data.totalMoney, res.data.description, res.data.totalMoneyStr );
             LODOP.ADD_PRINT_SETUP_BKIMG("<img border='0' src=" + imgUrl + ">");
             LODOP.SET_PREVIEW_WINDOW(1, 0, 0, 950, 700, "");
             LODOP.SET_SHOW_MODE("BKIMG_PRINT", 1);
             LODOP.SET_SHOW_MODE("HIDE_DISBUTTIN_SETUP", 1);//隐藏那些无效按钮
             LODOP.SET_PRINT_MODE("AUTO_CLOSE_PREWINDOW", 1);//打印后自动关闭预览窗口
             LODOP.PREVIEW();//打印模式
        });
    } 

    /**
     * 报销
     */
    getReimbursement(time, holderName, bankCode, feetype, reimbursementMoney, remark, totalMoneyStr):void{
        LODOP.SET_SHOW_MODE("BKIMG_WIDTH", 100);
        LODOP.PRINT_INIT("打印");
        LODOP.ADD_PRINT_TEXT(84, 555, 140, 22, time);//审核时间
        LODOP.SET_PRINT_STYLEA(0, "FontSize", 12);
        LODOP.SET_PRINT_STYLEA(0, "Alignment", 2);//居中
        LODOP.ADD_PRINT_TEXT(152, 50, 99, 28, holderName);//持卡人姓名
        LODOP.SET_PRINT_STYLEA(0, "FontSize", 12);
        LODOP.SET_PRINT_STYLEA(0, "Alignment", 2);
        LODOP.ADD_PRINT_TEXT(152, 152, 182, 41, bankCode);//银行卡号
        LODOP.SET_PRINT_STYLEA(0, "FontSize", 12);
        LODOP.SET_PRINT_STYLEA(0, "Alignment", 2);
        LODOP.ADD_PRINT_TEXT(152, 513, 152, 29, feetype);//付款方式
        LODOP.SET_PRINT_STYLEA(0, "FontSize", 12);
        LODOP.SET_PRINT_STYLEA(0, "Alignment", 2);
        LODOP.ADD_PRINT_TEXT(192, 263, 225, 29, totalMoneyStr);//报销金额(大写)
        LODOP.SET_PRINT_STYLEA(0, "FontSize", 12);
        LODOP.ADD_PRINT_TEXT(191, 539, 128, 27, reimbursementMoney);//报销金额
        LODOP.SET_PRINT_STYLEA(0, "FontSize", 12);
        LODOP.ADD_PRINT_TEXT(223, 158, 524, 50, remark);//事由
        LODOP.SET_PRINT_STYLEA(0, "FontSize", 12);
    }
    

}
angular.module("tms").controller("feeSettleManagentController", ["$scope", "feeService", "authorizationService", "valueService", "employeeService", "$ngBootbox" ,  "$state", "routeService",
 "LodopFuncsService","$location","commonService", IFeeSettleManagentController]);